package Game;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;


public class GUI extends JFrame {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 6411499808530678723L;
	private JButton playerOptions;
	private JButton language;
	private JButton connection;
	private JButton newGame;
	
	private JButton help;
	private UltimateTicTacToeField game = new UltimateTicTacToeField();
	private JTextArea chatField = new JTextArea();
	private LabeledTextField input = new LabeledTextField(Strings.getString("message"), "", false, 250, 26);
	private JButton send = new JButton(Strings.getString("send"));

	public GUI() {
		super("Ultimate Tic Tac Toe");
		String languageName = IO.loadString("languagename");
		String languageFile = IO.loadString("languagefile");
		if (languageFile != null && new File(languageFile).exists()) {
			IO.addLanguage(new File(languageFile));
			Strings.addStrings(IO.loadLanguage(new File(languageFile)));
		} else if (languageName != null && IO.getLanguage(languageName) != null) {
			Strings.addStrings(IO.loadLanguage(IO.getLanguage(languageName)));
		}
		
		JPanel window = new JPanel();
		window.setLayout(new BoxLayout(window, BoxLayout.Y_AXIS));
		
		JPanel menuBar = new MenuBar();
		menuBar.setLayout(new BoxLayout(menuBar, BoxLayout.X_AXIS));
		
		Player you = Player.getPlayerByID(Player.PlayerID.you);
		playerOptions = new JButton(you.getName(), new ImageIcon(Graphics.getGraphic(you.getSign().name()).getScaledInstance(26, 26, BufferedImage.SCALE_SMOOTH)));
		playerOptions.setMaximumSize(new Dimension(TicTacToeField.size / 2 + UltimateTicTacToeField.gap / 2, 26));
		playerOptions.setPreferredSize(new Dimension(TicTacToeField.size / 2 + UltimateTicTacToeField.gap / 2, 26));
		playerOptions.setMargin(new Insets(0, 0, 0, 0));
		playerOptions.setFocusable(false);
		playerOptions.setHorizontalAlignment(SwingConstants.LEFT);
		playerOptions.addActionListener(new PlayerOptionsPressed());
		
		language = new JButton(Strings.getString("lang"));
		language.setMaximumSize(new Dimension(TicTacToeField.size / 2 + UltimateTicTacToeField.gap / 2, 26));
		language.setPreferredSize(new Dimension(TicTacToeField.size / 2 + UltimateTicTacToeField.gap / 2, 26));
		language.setFocusable(false);
		language.addActionListener(new LanguagePressed());
		
		connection = new JButton(Strings.getString("connection"));
		connection.setMaximumSize(new Dimension(TicTacToeField.size / 2 + UltimateTicTacToeField.gap / 2, 26));
		connection.setPreferredSize(new Dimension(TicTacToeField.size / 2 + UltimateTicTacToeField.gap / 2, 26));
		connection.setFocusable(false);
		connection.addActionListener(new ConnectionPressed());
		
		newGame = new JButton(Strings.getString("newGame"));
		newGame.setMaximumSize(new Dimension(TicTacToeField.size / 2 + UltimateTicTacToeField.gap / 2, 26));
		newGame.setPreferredSize(new Dimension(TicTacToeField.size / 2 + UltimateTicTacToeField.gap / 2, 26));
		newGame.setFocusable(false);
		newGame.addActionListener(new NewGamePressed());
		
		
		
		help = new JButton("?");
		help.setMaximumSize(new Dimension(26, 26));
		help.setPreferredSize(new Dimension(26, 26));
		help.setMargin(new Insets(0, 0, 0, 0));
		help.setFocusable(false);
		help.addActionListener(new HelpPressed());
		
		menuBar.add(Box.createHorizontalStrut(UltimateTicTacToeField.gap / 2));
		menuBar.add(playerOptions);
		menuBar.add(language);
		menuBar.add(connection);
		menuBar.add(newGame);
		menuBar.add(Box.createHorizontalGlue());
		menuBar.add(help);
		
		JPanel mainPanel = new JPanel();
		mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.X_AXIS));
		
		JPanel chat = new JPanel();
		chat.setLayout(new BoxLayout(chat, BoxLayout.Y_AXIS));
		chatField.setEditable(false);
		JScrollPane chatFieldPane = new JScrollPane(chatField, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
		chatFieldPane.setPreferredSize(new Dimension(350, UltimateTicTacToeField.size - 26));
		chatFieldPane.setMaximumSize(new Dimension(350, UltimateTicTacToeField.size - 26));
		chatFieldPane.setBorder(BorderFactory.createLineBorder(new Color(85,147, 222), 1));
		chat.add(chatFieldPane);
		
		JPanel inputPanel = new JPanel();
		inputPanel.setLayout(new BoxLayout(inputPanel, BoxLayout.X_AXIS));
		SendPressed sendMessage = new SendPressed();
		inputPanel.add(input);
		input.getTextField().addActionListener(sendMessage);
		inputPanel.add(send);
		send.addActionListener(sendMessage);
		send.setMaximumSize(new Dimension(100, 26));
		send.setPreferredSize(new Dimension(100, 26));
		send.setFocusable(false);
		chat.add(inputPanel);
		
		mainPanel.add(game);
		mainPanel.add(chat);
		
		window.add(menuBar);
		window.add(mainPanel);
		
		addLine(Strings.getString("started"));
		this.getContentPane().add(window, BorderLayout.CENTER);
        this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        //this.setResizable(false);
        this.pack();
        this.setMinimumSize(this.getSize());
        this.setLocationRelativeTo(null);
        this.setVisible(true);
	}
	
	public void dispose() {
		super.dispose();
		Main.mainFinal();
	}
	
	public void updateField(int x, int y) {
		game.repaint();
	}
	
	public void connectionLost() {
		
	}
	
	public void newGame() {
		game.repaint();
	}
	
	public void addLine(String message) {
		chatField.setText(chatField.getText() + message + "\n");
	}
	
	private class SendPressed implements ActionListener {

		public void actionPerformed(ActionEvent e) {
			Main.sendMessage(input.getValue());
			GUI.this.input.setValue("");
		}
		
	}
	
	private class PlayerOptionsPressed implements ActionListener {

		public void actionPerformed(ActionEvent e) {
			Player you = Player.getPlayerByID(Player.PlayerID.you);
			Player opponent = Player.getPlayerByID(Player.PlayerID.opponent);
			Object[] options = {new ImageIcon(Graphics.getGraphic(you.getSign().name())),
								new ImageIcon(Graphics.getGraphic(opponent.getSign().name())),
                    			Strings.getString("cancel")};
			LabeledTextField name = new LabeledTextField(Strings.getString("name"), you.getName(), false, 246, 26);
			int n = JOptionPane.showOptionDialog(GUI.this,
											     name,
											     Strings.getString("options"),
											     JOptionPane.YES_NO_OPTION,
											     JOptionPane.PLAIN_MESSAGE,
											     null,
											     options,
											     Strings.getString("cancel"));
			if (n == 0 || n == 1) {
				you.setName(StringFilter.filterString(name.getValue()));
			}
			if (n == 1) {
				Player.Sign temp = opponent.getSign();
				opponent.setSign(you.getSign());
				you.setSign(temp);
			}
			GUI.this.playerOptions.setIcon(new ImageIcon(Graphics.getGraphic(you.getSign().name()).getScaledInstance(26, 26, BufferedImage.SCALE_SMOOTH)));
			GUI.this.playerOptions.setText(you.getName());	
			GUI.this.game.repaint();
		}
		
	}
	
	private class LanguagePressed implements ActionListener {

		public void actionPerformed(ActionEvent e) {
			JLabel label = new JLabel(Strings.getString("whichLanguage"));
			label.setAlignmentX(0f);
			JComboBox<String> select = new JComboBox<String>(IO.getLanguages().keySet().toArray(new String[0]));
			select.setAlignmentX(0f);
			select.setSelectedItem(Strings.getString("lang"));
			JButton custom = new JButton(Strings.getString("customLanguage"));
			custom.addActionListener(new CustomLanguagePressed(select));
			JPanel dialogue = new JPanel();
			dialogue.setLayout(new BoxLayout(dialogue, BoxLayout.Y_AXIS));
			dialogue.add(label);
			dialogue.add(Box.createVerticalStrut(5));
			dialogue.add(select);
			Object[] options = {Strings.getString("ok"), Strings.getString("cancel"), custom};
			int n = JOptionPane.showOptionDialog(GUI.this,
												 dialogue,
												 Strings.getString("language") + "?",
											     JOptionPane.YES_NO_OPTION,
											     JOptionPane.PLAIN_MESSAGE,
											     null,
											     options,
											     Strings.getString("ok"));
			if (n == 0) {
				Strings.addStrings(IO.loadLanguage(IO.getLanguage((String)select.getSelectedItem())));
				IO.saveString("languagename", (String)select.getSelectedItem());
				IO.saveString("languagefile", IO.getLanguage((String)select.getSelectedItem()).getPath());
				language.setText(Strings.getString("lang"));
				connection.setText(Strings.getString("connection"));
				newGame.setText(Strings.getString("newGame"));
				send.setText(Strings.getString("send"));
				input.setName(Strings.getString("message"));
			}
		}
		
	}
	
	private class CustomLanguagePressed implements ActionListener {
		
		private JComboBox<String> select;
		
		public CustomLanguagePressed(JComboBox<String> select) {
			this.select = select;
		}

		public void actionPerformed(ActionEvent e) {
			File file = IO.askFile(new String[]{"lang"}, IO.OPEN);
			if (file != null) {
				IO.addLanguage(file);
				select.addItem(file.getName().substring(0, file.getName().length() - 5));
				select.setSelectedItem(file.getName().substring(0, file.getName().length() - 5));
			}
		}
		
	}
	
	private class ConnectionPressed implements ActionListener {

		public void actionPerformed(ActionEvent e) {
			LabeledTextField textfield = new LabeledTextField("IP", "", false, 237, 26);
			LabeledSpinner spinner = new LabeledSpinner("Port", 25565, 1, 0xFFFF, 237, 26);
			JPanel dialogue = new JPanel();
			dialogue.setLayout(new BoxLayout(dialogue, BoxLayout.Y_AXIS));
			dialogue.add(textfield);
			dialogue.add(Box.createVerticalStrut(5));
			dialogue.add(spinner);
			Object[] options = {Strings.getString("connect"), Strings.getString("wait"), Strings.getString("cancel")};
			int n = JOptionPane.showOptionDialog(GUI.this,
												 dialogue,
												 Strings.getString("connection") + "?",
											     JOptionPane.YES_NO_OPTION,
											     JOptionPane.PLAIN_MESSAGE,
											     null,
											     options,
											     Strings.getString("cancel"));
			if (n == 0) {
				Main.connectToServer(textfield.getName(), spinner.getValue());
			} else if (n == 1) {
				Main.createServer(spinner.getValue());
			}
		}
		
	}
	
	private class NewGamePressed implements ActionListener {

		public void actionPerformed(ActionEvent e) {
			Main.newGame(Player.PlayerID.you);
		}
		
	}
	
	private class HelpPressed implements ActionListener {

		public void actionPerformed(ActionEvent e) {
			JPanel dialogue = new JPanel();
			dialogue.setLayout(new BoxLayout(dialogue, BoxLayout.Y_AXIS));
			JLabel informations = new JLabel(Strings.getString("informationDialoge"));
			JLabel link = new LinkedLabel(Strings.getString("moreInformations") ,"http://mathwithbaddrawings.com/2013/06/16/ultimate-tic-tac-toe/");//new JLabel(Strings.getString("moreInformations"));
			dialogue.add(informations);
			dialogue.add(link);
			Object[] options = {Strings.getString("clearData"), Strings.getString("close")};
			int n = JOptionPane.showOptionDialog(GUI.this,
												 dialogue,
												 Strings.getString("informations"),
											     JOptionPane.YES_NO_OPTION,
											     JOptionPane.PLAIN_MESSAGE,
											     null,
											     options,
											     Strings.getString("close"));
			if (n == 0) {
				IO.clearAllStrings();
			}
		}
		
	}

}
